package com.fangxing.module.user.service;

import com.fangxing.config.SysCfgParam;
import com.fangxing.module.user.dao.CheckCodeRepository;
import com.fangxing.module.user.entity.CheckCodeEntity;
import com.fangxing.util.RandomCodeGenerator;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;

public class CheckCodeService {

    @Autowired
    private CheckCodeRepository checkCodeRepository;


    public String genCode(String phoneNo, int length) {
        String code = RandomCodeGenerator.genCode(length);

        CheckCodeEntity entity = new CheckCodeEntity();
        entity.setCellphone(phoneNo);
        entity.setCode(code);
        entity.setGenTime(new Date().getTime());
        entity.setValid(true);

        save(entity);

        //Todo 可是使用手机发送验证码
        return code;
    }

    public boolean check(String phone, String code){
        CheckCodeEntity entity = checkCodeRepository.findByCellphone(phone);
        if (isExpiredCheckCode(entity) == false
                && code.equals(entity.getCode())
                && entity.getValid() == true) {
            entity.setValid(false);
            entity.setDeleted(true);
            return true;
        }

        return false;
    }

    private void save(CheckCodeEntity entity) {
        //Todo:这里用redis比较好，可以借用redis的自动覆盖或者过期功能。
        checkCodeRepository.save(entity);
    }

    private boolean isExpiredCheckCode(CheckCodeEntity entity) {
        if (new Date().getTime() - entity.getGenTime() > SysCfgParam.CHECK_CODE_VALID_TIME_LEN) {
            return true;
        }

        return false;
    }

}
